﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace System.Windows.Media.DirectShow.Filters
{
    public abstract class BaseFilter : IBaseFilter
    {
        private FilterState _state = FilterState.Stopped;
        private IFilterGraph _graph;
        private PinsCollection _pins;
        private IReferenceClock _syncSource;
        private SingleThreadPool job = new SingleThreadPool();

        #region IBaseFilter Members

        public IFilterGraph Graph
        {
            get { return _graph; }
            internal set
            {
                _graph = value;
                SetGraph(value);
            }
        }

        public PinsCollection Pins
        {
            get
            {
                if (_pins == null)
                {
                    _pins = new PinsCollection();
                }
                return _pins;
            }
        }

        protected virtual void SetGraph(IFilterGraph graph)
        {
        }

        IPinsEnumerable IBaseFilter.Pins
        {
            get { return this.Pins; }
        }

        #endregion

        #region IMediaFilter Members

        public void Pause()
        {
            if (_state != FilterState.Paused)
            {
                PauseInternal();
                _state = FilterState.Paused;
            }
        }

        public void Run(TimeSpan start)
        {
            if (_state != FilterState.Running)
            {
                _state = FilterState.Running;

                RunInternal(start);
            }
        }

        public FilterState State
        {
            get { return _state; }
        }

        public void Stop()
        {
            if (_state != FilterState.Stopped)
            {
                StopInternal();

                _state = FilterState.Stopped;
            }
        }

        public IReferenceClock SyncSource
        {
            get
            {
                return _syncSource;
            }
            set
            {
                _syncSource = value;
            }
        }

        #endregion

        #region IMediaObject Members

        public abstract string Name
        {
            get;
        }

        #endregion

        #region Protected

        protected void QueueWork(WaitCallback callback)
        {
            this.QueueWork(callback, null);
        }

        protected void QueueWork(WaitCallback callback, object state)
        {
            this.job.QueueUserWorkItem(callback, state);
        }

        protected virtual void PauseInternal()
        {
            try
            {
                this.Pins.ExecuteAction<BasePin>(p => p.Active());
            }
            catch (Exception e)
            {
                HandleException("Error pausing filter", e);
            }
        }

        protected virtual void StopInternal()
        {
            try
            {
                this.job.Abort();
                this.Pins.OrderBy(p => p.Direction).ExecuteAction<BasePin>(p => p.Inactive());
            }
            catch (Exception e)
            {
                HandleException("Error stopping filter", e);
            }
        }

        protected virtual void RunInternal(TimeSpan start)
        {
            try
            {
                if (this.State == FilterState.Paused)
                    this.Pins.OrderByDescending(p => p.Direction).ExecuteAction<BasePin>(p => p.Active());
                else
                    this.Pins.OrderByDescending(p => p.Direction).ExecuteAction<BasePin>(p => p.Run(start));
            }
            catch (Exception e)
            {
                HandleException("Error running filter", e);
            }
        }

        protected void VerifyAccess()
        {
            if (!this.Graph.Dispatcher.CheckAccess())
                throw new InvalidOperationException("Invalid thread access. Only ui thread is allowed");
        }
        #endregion

        private void HandleException(string message, Exception e)
        {
            if (e is ThreadAbortException) return;

            var d = new DirectShowFilterException(message, this, e);
            if (this.Graph is IMediaEvent)
                ((IMediaEvent)this.Graph).NotifyEvent(new ErrorEventArgs(this, e));
            else
                throw d;
        }
    }
}
